package server.web.api.webuser;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import server.web.HttpServer;
import server.web.WebUser;

public class Login extends HttpServlet {
    private static final long serialVersionUID = 3113410087797105941L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession se = req.getSession(true);

        resp.setContentType("text/plain");
        if (se.isNew() || (se.getAttribute("user") == null || ((WebUser) se.getAttribute("user")).isDead())) {
            Map<String, String[]> pa = req.getParameterMap();
            try {
                if (pa.containsKey("name") && pa.containsKey("uid")) {
                    String name = pa.get("name")[0];
                    long uid = Long.parseLong(pa.get("uid")[0]);

                    se.setAttribute("name", name);
                    se.setAttribute("uid", uid);
                    se.setAttribute("user", HttpServer.createWebUser(name, uid));
                    se.setMaxInactiveInterval(30);
                    resp.getWriter().print("true");
                    return;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        resp.getWriter().print("false");
    }
}